package com.jxt.app.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jxt.app.entity.Apdialog;
import com.jxt.app.entity.ApdialogExample;
import com.jxt.app.entity.Apiphone;
import com.jxt.app.entity.Apmessages;
import com.jxt.app.entity.ApmessagesExample;
import com.jxt.app.entity.Apnews;
import com.jxt.app.entity.ApnewsExample;
import com.jxt.app.entity.UserObj;
import com.jxt.app.service.ApDialogService;
import com.jxt.app.service.ApMessageService;
import com.jxt.app.service.NewsService;
import com.jxt.app.util.Constant;
import com.jxt.app.util.DateHelper;
import com.jxt.app.util.HTTPUtil;
import com.jxt.app.util.MainApnsSend;
import com.jxt.app.util.Page;
import com.jxt.app.vo.ApdialogVo;
import com.jxt.app.vo.ApmessagesVo;

@Controller
public class MessageController {
	private MessageController(){
		System.out.print("启动信息控制器！");
		//MainApnsSend mainApnsSend=new MainApnsSend();
		MainApnsSend.Autorun();
		MainApnsSend.MsgClearTimerTaskAutorun();
		MainApnsSend.ResTimerTaskTaskAutorun();
	}
	// 日志记录器
	private static final Logger logger = Logger.getLogger(MessageController.class);


	
	@Resource
	private ApMessageService apMessageService;
	
	@Resource
	private ApDialogService apDialogService;
	/**
	 * 查询发送给某人的信息列表
	 * @param page
	 * @param pageSize
	 * @param requset
	 * @param model
	 * @param isread 0为未读消息  1为已读
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/app/msg/list/{userid}/{isread}/{num}",method=RequestMethod.GET) 
	public String megList(@PathVariable int num,@PathVariable String userid,@PathVariable Byte isread,HttpServletRequest requset, Model model) throws UnsupportedEncodingException{
		
		System.out.print("-------------------查询消息！------------------\n");
		
//		ApmessagesExample example=new ApmessagesExample();
//		example.setId((long)0);
//		example.setId_Indicator(ApmessagesExample.EXAMPLE_GREATER_THAN);
//		example.setIsread(isread);
//		example.setIsread_Indicator(ApmessagesExample.EXAMPLE_EQUALS);
//	
//		Page apnewsList = null;
//		
//		List<ApmessagesVo> msgList=null;
//		
//		HashMap<String, Object> parms=new HashMap<String, Object>();
//		parms.put("isread", isread);
//		parms.put("num", num);
//		parms.put("userid", userid);
//		try {
//			msgList=apMessageService.queryUnreadMsg(parms);
//			System.out.print("----------------------\n");
//			System.out.print("====++++++++"+msgList.size()+"----------------------\n");
//			System.out.print("----------------------\n");
//			//apnewsList = apMessageService.findListByExample(example, page, pageSize);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		List<ApmessagesVo> msgList=new ArrayList<ApmessagesVo>();;
		
		try{
			Apiphone apiphone=MainApnsSend.apIphoneUser.get(userid);
			if(apiphone!=null){
				apiphone.setLastvist(new Date());//设置用户最近访问时间判断是否在线还是下线
			}
			
			msgList=MainApnsSend.cacheApMessages.get(userid);
			apMessageService.updateMassageList(msgList, userid);

			model.addAttribute("result", msgList);
			MainApnsSend.cacheApMessages.put(userid, new ArrayList<ApmessagesVo>());
		}catch(Exception e){
			logger.debug(e);
			model.addAttribute("result", null);
		}
	
		return "megList";
	}
	
	
	@RequestMapping(value="/app/msg/test",method=RequestMethod.GET) 
	public String addMsg(HttpServletRequest requset, Model model) throws UnsupportedEncodingException{
	
	
		return "buy";
	}
	
	
	
	
	 private String getError(String message) {
			JSONObject obj = new JSONObject();
			obj.put("code", -1001);
			obj.put("message", message);
			return obj.toString();
		}
	 
	 /**
	  * 根据会话ID查询会话
	  * @param apdialogId
	  * @param response
	  * @param requset
	  * @param model
	  * @throws UnsupportedEncodingException
	  */
	 @RequestMapping(value="/app/msg/queryDialogIdById",method=RequestMethod.GET) 
	 public void queryDialogIdById(String dialogid,HttpServletResponse response,HttpServletRequest requset, Model model) throws UnsupportedEncodingException
	 {
		 	response.setContentType("text/html; charset=UTF-8");
		 
			PrintWriter out = null;
			try {
				out = response.getWriter();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 
			
			JSONObject obj = new JSONObject();
			
		 try{
			 ApdialogExample apdialogExample=new ApdialogExample();
			 
			 apdialogExample.setDialogid(dialogid);
			 apdialogExample.setDialogid_Indicator(ApdialogExample.EXAMPLE_EQUALS);
			 
			List<Apdialog>  dilogList=apDialogService.listModel(apdialogExample);
			if(null!=dilogList&&dilogList.size()>0){
				Apdialog apdialog=dilogList.get(0);
				
				
				ApdialogVo apdialogVo=new ApdialogVo();
				apdialogVo.setDialogid(apdialog.getDialogid());
				apdialogVo.setDialogname(apdialog.getDialogname());
				apdialogVo.setTime(apdialog.getTime().getTime());
				
				obj.put("code", 1001);
				obj.put("result", apdialogVo);
				
			}else{
				obj.put("code", -1001);
			}
		 }catch(Exception e){
			 e.printStackTrace();
			 obj.put("code", -1001);
		 }
		 out.println(obj.toString());
	 }
	 
	 
	 
	 
	 
	 
	 /**
	  * 创建对话群
	  * @param apdialog
	  * @param response
	  * @param requset
	  * @param model
	  * @throws UnsupportedEncodingException
	  */
	 @RequestMapping(value="/app/msg/getDialogId",method=RequestMethod.POST) 
	 public void getDialogId(Apdialog apdialog,HttpServletResponse response,HttpServletRequest requset, Model model) throws UnsupportedEncodingException
	 {
		 	response.setContentType("text/html; charset=UTF-8");
		 	PrintWriter out = null;
			try {
				out = response.getWriter();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 
			
			JSONObject obj = new JSONObject();
			
		 	if(null==apdialog){
		 		 obj.put("code", -1002);
		 		 return;
		 	}	
		 	
		 	if(null==apdialog.getReceiveid()&&""==apdialog.getReceiveid()){
		 		obj.put("code", -1002);
		 		obj.put("msg", "会话接受者不能为NULL");
		 		return;
		 	}
 	
			 try{
				 String dialogId=UUID.randomUUID().toString().replace("-", "");
				 apdialog.setDialogid(dialogId);
				 apdialog.setTime(new Date());
				 int ret= apDialogService.insertModel(apdialog);
				 if(ret==1){
					 obj.put("code", 1001);
				 }else{
					 obj.put("code", -1001);
				 }
				 obj.put("dialogId", dialogId);
				 
			 }catch(Exception e){ 
				 obj.put("code", -1001);
				
			 }
			 
			out.println(obj.toString());
		 
	 }
	 
	 /**
	  * 信息推送接口
	  * @param filename
	  * @param msg
	  * @param infoType 0信息
	  * @param receiveId
	  * @param filetype
	  * @param type
	  * @param width
	  * @param p
	  * @param a
	  * @param upImg
	  * @param request
	  * @param response
	  * @param model
	  * @throws IOException
	  * @throws FileUploadException
	  */
	 @RequestMapping(value="/app/msg/upload",method=RequestMethod.POST) 
	 public void upload_json(Short canReply,long sendid,String sendname,String sendtype,String filename,String msg,String dialogId,Short infoType,String receiveId,@RequestParam(required = false, defaultValue = "1")int type,@RequestParam(required = false, defaultValue = "500")int width,String upImg,HttpServletRequest request,HttpServletResponse response,Model model) throws IOException, FileUploadException {   
		 { 
			 
			 try{	 
			 
			 Apmessages apMessages=new Apmessages();
			 apMessages.setInfotype(infoType);
			 apMessages.setCanReply(canReply);
			 apMessages.setSendTime(new Date());
			 apMessages.setIschecked((byte)0);
			 apMessages.setIsread((byte)0);
			 apMessages.setIspush((byte)0);
			 apMessages.setSysflag((byte)0);
			 if(null==dialogId||"".equals(dialogId)){
				 dialogId=UUID.randomUUID().toString();
			 }
			 apMessages.setDialogid(dialogId);
				
			
			 response.setContentType("text/html; charset=UTF-8");
			 PrintWriter out = response.getWriter(); 
			 if(infoType==1||infoType==2){
			//文件保存目录路径
			 String savePath = request.getSession().getServletContext().getRealPath("/") + "attached/";

			 //文件保存目录URL
			 String saveUrl  = request.getContextPath() + "/attached/";

			 //定义允许上传的文件扩展名
			 HashMap<String, String> extMap = new HashMap<String, String>();
			 extMap.put("image", "gif,jpg,jpeg,png,bmp");
			 extMap.put("flash", "swf,flv");
			 extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
			 extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

			 //最大文件大小
			 long maxSize = 1000000;

			

			 if(!ServletFileUpload.isMultipartContent(request)){
			 	out.println(getError("请选择文件。"));
			 	return;
			 }
			 //检查目录
			 File uploadDir = new File(savePath);
			 if(!uploadDir.isDirectory()){
			 	out.println(getError("上传目录不存在。"));
			 	return;
			 }
			 //检查目录写权限
			 if(!uploadDir.canWrite()){
			 	out.println(getError("上传目录没有写权限。"));
			 	return;
			 }

			 String dirName = request.getParameter("dir");
			 if (dirName == null) {
			 	dirName = "image";
			 }
			 if(!extMap.containsKey(dirName)){
			 	out.println(getError("目录名不正确。"));
			 	return;
			 }
			 //创建文件夹
			 savePath += dirName + "/";
			 saveUrl += dirName + "/";
			 File saveDirFile = new File(savePath);
			 if (!saveDirFile.exists()) {
			 	saveDirFile.mkdirs();
			 }
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			 String ymd = sdf.format(new Date());
			 savePath += ymd + "/";
			 saveUrl += ymd + "/";
			 File dirFile = new File(savePath);
			 if (!dirFile.exists()) {
			 	dirFile.mkdirs();
			 }

			 FileItemFactory factory = new DiskFileItemFactory();
			 ServletFileUpload upload = new ServletFileUpload(factory);
			 upload.setHeaderEncoding("UTF-8");
			 
			 //转型为MultipartHttpRequest(重点的所在)   
	         MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;   
	         //  获得第1张图片（根据前台的name名称得到上传的文件）    
	         List<MultipartFile> imgFileList  =  multipartRequest.getFiles("file");
	           
	         //定义一个数组，用于保存可上传的文件类型   

			// List items = upload.parseRequest(request);
	         List items=imgFileList;
			 Iterator itr = items.iterator();
		    for(MultipartFile imgFile:imgFileList){
			 	//FileItem item = (FileItem) itr.next();
			 	//String fileName = imgFile.getOriginalFilename();
		    	String fileName=filename;
			 	long fileSize = imgFile.getSize();
					 		
						//检查文件大小
				 	if(imgFile.getSize() ==0){
				 			out.println(getError("上传文件为0字节。"));
				 			return;
				 	}
			 		//检查文件大小
			 		if(imgFile.getSize() > maxSize){
			 			out.println(getError("上传文件大小超过限制。"));
			 			return;
			 		}
			 		//检查扩展名
			 		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			 		if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
			 			out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
			 			return;
			 		}

			 		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			 		String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
			 		try{
			 			File uploadedFile = new File(savePath, newFileName);
			 			imgFile.transferTo(uploadedFile); 
			 		}catch(Exception e){
			 			out.println(getError("上传文件失败。"));
			 			return;
			 		}			 		
			 		apMessages.setFileurl(saveUrl + newFileName);
			 		apMessages.setFilename(filename);
			 		JSONObject obj = new JSONObject();
			 		Apmessages	result=apMessageService.save(apMessages,sendid,sendname,sendtype);//发送成功
			 		
			 		
			 		obj.put("msgid", result.getId());
			 		obj.put("dialogId", dialogId);
				 	obj.put("code", 1001);
				 	obj.put("url", saveUrl + newFileName);
				 	out.println(obj.toString());
				 	logger.debug("----------发送图片音频成功-----------");
			 	
		    	}
			 
			 }
			 else{	
				 	apMessages.setMsg(msg);
					JSONObject obj = new JSONObject();
					Apmessages	result=apMessageService.save(apMessages,sendid,sendname,sendtype);//发送文字成功
					
					
					
					obj.put("msgid", result.getId());
			 		obj.put("dialogId", dialogId);
				 	obj.put("code", 1001);
				 	out.println(obj.toString()); 
				 	logger.debug("----------发送文字成功-----------");
		    	}
			 }catch(Exception e){
				 	e.printStackTrace();
				 	PrintWriter out = response.getWriter(); 
				 	JSONObject obj = new JSONObject();
		 			obj.put("code", -1001);
		 			out.println(obj.toString());
		 			
		 	}
		 }
		
	}
	/**
	 * android 消息推送 ---暂时废弃
	 * @param title
	 * @param message
	 * @param uri
	 * @param requset
	 * @param response
	 * @param model
	 * @throws IOException
	 */
    @RequestMapping(value="/app/msg/android/pushss",method=RequestMethod.GET) 
	public void pushAndroidMessage22( String title, String message, String uri,String type,String infoType,String pushObj,HttpServletRequest requset, HttpServletResponse response,Model model) throws IOException{
			
//			model.addAttribute("message", message);
//			model.addAttribute("title", title);
//			model.addAttribute("uri", uri);
			String result="";
			pushObj="{\"obj\":{\"schoolId\":\"12\",\"gradeId\":[\"22\",\"32\"],\"classId\":[\"22\",\"32\"],\"roleId\":[\"22\",\"32\"],\"memberId\":[\"22\",\"32\"]}}";
			if(null==pushObj){
				result = HTTPUtil.getHttpResult(Constant.basePushUrl+"/notification.do", "action=push"+"&message="+message+"&title="+title+"&uri="+uri+"&type="+type+"&infoType="+infoType);
			}else{
				JSONObject jo = JSONObject.fromObject(pushObj);
				Object returnObj=jo.get("obj");
				UserObj obj=(UserObj) JSONObject.toBean((JSONObject) returnObj, UserObj.class);
				result = HTTPUtil.getHttpResult(Constant.basePushUrl+"/notification.do", "action=push"+"&message="+message+"&title="+title+"&uri="+uri+"&type="+type+"&infoType="+infoType);	
			}
			response.setContentType("text/javascript;charset=UTF-8");
		   	PrintWriter out = response.getWriter(); 
		   	out.write(result);
	 		out.close();
			System.out.print(result);
	
		}
    
	/**
	 * android 消息推送
	 * @param title
	 * @param message
	 * @param uri
	 * @param requset
	 * @param response
	 * @param model
	 * @throws IOException
	 */
    @RequestMapping(value="/app/msg/android/push",method=RequestMethod.GET) 
	public void pushAndroidMessage( String title, String message, String uri,String type,String infoType,String pushObj,HttpServletRequest requset, HttpServletResponse response,Model model) throws IOException{
			
//			model.addAttribute("message", message);
//			model.addAttribute("title", title);
//			model.addAttribute("uri", uri);
			String result="";
			//pushObj="{\"obj\":{\"schoolId\":\"12\",\"gradeId\":[\"22\",\"32\"],\"classId\":[\"22\",\"32\"],\"roleId\":[\"22\",\"32\"],\"memberId\":[\"22\",\"32\"]}}";
			if(null==pushObj){
				result = HTTPUtil.getHttpResult(Constant.romotePushUrl+"/notification.do", "action=push"+"&message="+message+"&title="+title+"&uri="+uri+"&type="+type+"&infoType="+infoType);
			}else{
				if(!"".equals(pushObj)){
					result = HTTPUtil.getHttpResult(Constant.romotePushUrl+"/notification.do", "action=push"+"&message="+message+"&title="+title+"&uri="+uri+"&type="+type+"&infoType="+infoType+"&username="+pushObj+"&broadcast=N");	
			
				}
			}
			response.setContentType("text/javascript;charset=UTF-8");
		   	PrintWriter out = response.getWriter(); 
		   	out.write(result);
	 		out.close();
			System.out.print(result);
	
		}
    
    
    
    @RequestMapping(value="/app/getobj",method=RequestMethod.GET)
    public String test( String title, String message, String uri,String pushObj,HttpServletRequest requset, HttpServletResponse response,Model model) throws IOException{
    	UserObj obj=new UserObj();	
    	obj.setSchoolId("12");
    	List<String> gradeId=new ArrayList<String>();
    	gradeId.add("22");
    	gradeId.add("32");
    	
    	List<String> classId=new ArrayList<String>();
    	classId.add("22");
    	classId.add("32");
    	
    	List<String> memberId=new ArrayList<String>();
    	memberId.add("22");
    	memberId.add("32");
    	
    	obj.setGradeId(gradeId);
    	obj.setClassId(classId);
    	obj.setMemberId(memberId);
    	
    	
    	model.addAttribute("obj", obj);
    	return "obj";
    		
    	}
    
    
    public static void main(String[] args){
    	MessageController messageController=new MessageController();
    	try {
			messageController.pushAndroidMessage("","","","","","",null,null,null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    
    /**
     * iphone 消息推送接口
     * @param idList id1,id2,id3
     * @param title
     * @param message
     * @param uri
     * @param requset
     * @param response
     * @param model
     * @throws IOException
     */
    @RequestMapping(value="/app/msg/iphone/push",method=RequestMethod.GET) 
	public void pushIphoneMessage(String idList,String title, String message, String uri,HttpServletRequest requset, HttpServletResponse response,Model model) throws IOException{
		response.setContentType("text/javascript;charset=UTF-8");
	   	PrintWriter out = response.getWriter(); 
	   	String result="{\"reult\",\"10001\"}";
    	try{
    		MainApnsSend.sendCommerceAPNSByIdList(idList, title, "1", "");
    		 result="{\"reult\",\"10001\"}";
    	
    	}catch(Exception e){
    		
    		result="{\"reult\",\"-10001\"}";
    	}
	
		   	out.write(result);
	 		out.close();
			System.out.print(result);
	
		}
	
}
